package com.twu.biblioteca;

public class LoginState implements State {

    private static User currentUser;

    public State executeStateBehaviour(UserInterface userInterface, Database database) {

        userInterface.write(new Output("Please Enter Your User Number:"));

        if(!verifyUsername(database, userInterface.read())) {
            userInterface.write(new Output("The User Number You entered Does Not Exist."));
            return new MenuState();
        }

        userInterface.write(new Output("Please Enter Your Password:"));

        if (!verifyPassword(userInterface.read())) {
            setCurrentUser(null);
            userInterface.write(new Output("The Password You Entered is Incorrect."));
            return new MenuState();
        }

        userInterface.write(new Output("You Have Successfully Logged In."));

        return new MenuState();

    }

    public static void setCurrentUser(User user) {
        currentUser = user;
    }

    public static User currentUser() {
        return currentUser;
    }

    private boolean verifyUsername(Database database, Input input) {

        for (User user : database.userList()) {

            if (input.string().equals(user.userNumber())) {
                setCurrentUser(user);
                return true;
            }

        }

        return false;
    }

   private boolean verifyPassword(Input input) {

       if (currentUser.password().equals(input.string())) {
           return true;
       } else {
           return false;
       }

   }

}
